const util = require('../../utils/util')
let p

Page({

	data: {
		years: [],
		yearIndex: 0,
		stuCredit: 0,
		stuGPA: 0,
		loadingPanel: {
			tip: '同步中'
		}
	},

	temp: {
		syncing: false
	},

	onLoad: function (options) {
		p = this
		util.userLogin({
			p,
			scene: 'other',
			complete: () => {
				util.showNotices(p)
				p.getStuScore({
					success: (data) => {
						p.setStuScore(data)
						util.hideLoadingPanel(p)
						p.temp.syncing = false
					},
					fail: (code, msg) => {
						util.hideLoadingPanel(p)
						p.temp.syncing = false
						util.error('同步失败', util.errorHandler(code, msg))
					}
				})
			},
			fail: (title, msg) => {
				wx.navigateBack({
					delta: 1
				})
				util.error(title, msg)
			},
			notBind: () => {
				util.modal('绑定提示', '只有登录和绑定身份后才能使用此功能哦，即将跳转到主页', () => {
					wx.switchTab({
						url: '/pages/home/home'
					})
				})
			}
		})
	},

	onUnload: () => {
		util.unloadPage('score')
	},

	setStuScore: (scoreData) => {
		let { courseYear, stuCredit, stuGPA, scoreList, certScoreList } = scoreData
		const temp = Object.keys(scoreList).concat(Object.keys(certScoreList))
		let years = []
		for (let year of temp)
			if (years.indexOf(year) == -1)
				years.push(year)
		let yearIndex = years.indexOf(courseYear)
		if (years.length > 0) {
			if (yearIndex == -1) {
				yearIndex = years.length - 1
				courseYear = years[yearIndex]
			}
		}
		else
			yearIndex = 0
		p.setData({
			years,
			yearIndex,
			stuCredit,
			stuGPA,
			scoreList,
			certScoreList
		})
		wx.setNavigationBarTitle({
			title: `${courseYear}学年成绩`,
		})
	},

	getStuScore: (obj) => {
		const {success, fail, sync} = obj
		p.temp.syncing = true
		util.request({
			source: 'score',
			method: sync ? 'put' : 'get',
			uri: 'user/student/score',
			data: {
				session: util.globalData('session')
			},
			success: (data) => {
				success(data)
			},
			fail
		})
	},

	changeScoreYear: (e) => {
		const index = e.detail.current
		const { scoreList } = p.data
		wx.setNavigationBarTitle({
			title: `${Object.keys(scoreList)[index]}学年成绩`,
		})
	},

	showHelp: () => {
		util.modal('功能说明', '毕业要求的学分是至少修满134分，默认显示本学年的成绩，左右滑动能够切换成绩的学年')
	},

	onPullDownRefresh: () => {
		wx.stopPullDownRefresh()
		if (p.temp.syncing)
			return
		wx.showModal({
			title: '同步最新成绩',
			content: '是否现在同步您在教务系统最新的成绩数据？',
			success: (res) => {
				if (res.confirm) {
					util.showLoadingPanel(p, '同步中')
					p.getStuScore({
						success: (data) => {
							p.setStuScore(data)
							util.hideLoadingPanel(p)
							p.temp.syncing = false
						},
						fail: (code, msg) => {
							util.hideLoadingPanel(p)
							p.temp.syncing = false
							util.error('同步失败', util.errorHandler(code, msg))
						},
						sync: true
					})
				}
			}
		})
	},

	onShareAppMessage: function () {
		return {
			title: '用创新盒子，查成绩快人一步！',
			path: '/pages/score/score'
		}
	}

})